package com.zdya.combatdocuments.p2pNetwork;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdya.combatdocuments.component.CombatDocumentConfig;
import com.zdya.combatdocuments.constant.Constants;
import com.zdya.combatdocuments.entity.*;
import com.zdya.combatdocuments.ethereum.EthChain;
import com.zdya.combatdocuments.exception.BusinessException;
import com.zdya.combatdocuments.mapper.*;
import com.zdya.combatdocuments.util.AjaxResult;
import com.zdya.combatdocuments.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.*;

@Service
@Slf4j
public class HandleService {
    @Lazy
    @Autowired
    NodeUtil node;
    @Autowired
    P2pClient p2pClient;
    @Autowired
    UserChatMapper userChatMapper;
    @Autowired
    NetworkUserMapper networkUserMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    DocumentMapper documentMapper;
    @Autowired
    BroadcastMapper broadcastMapper;
    @Autowired
    GradeMapper gradeMapper;
    @Autowired
    DocApprovalLimitMapper docApprovalLimitMapper;
    @Autowired
    NetworkMapper networkMapper;
    @Autowired
    ChainDataMapper chainDataMapper;


    @Value("${server.port}")
    private String port;


    /**
     * type定义
     * 0：向其他节点推送nodeList，以供连接
     * 1:推送文本信息
     * 2：推送图片信息
     * 3：推送文件信息
     * 4：推送文书信息
     * 5：推送群发公告消息
     * 6：向前端推送UserList
     * 7：转发至主节点消息
     * 8：向前端推送用户新增信息
     * 10:区块高度、阶段信息、用户人数、主节点IP信息
     * 11:阶段更新处理
     * 12：从节点上链时向主节点发送信息，主节点进行缓存插表处理
     * 13：从节点更新链上信息时，向主节点发送，进行更新操作
     * 14:主节点定时向从节点推送上链list，从节点接受置内存，并定时更新表
     * */
    /**
     * 处理socket消息，文本类型/群连方法
     *
     * @param webSocket
     * @param msg
     */
    //ip 改id
    public void handleMessage(WebSocket webSocket, String msg) {
        try {
            String ipAddress = node.getIpByWs(webSocket);
            log.info("接收到IP地址为：" + ipAddress + "的p2p消息：" + msg);
            //IP相同，判断是本机浏览器推送的msg，解析转发msg(ip+type+content+netId)
            if (ipAddress == "127.0.0.1" || (ipAddress).equals("127.0.0.1")) {
                JSONObject jsonObject = JSONUtil.parseObj(msg);
                Long id = jsonObject.getLong("id");
                jsonObject.remove("id");
                WebSocket ws = node.getWebSocketById(id, node.getIdToIpList());
                UserChat userChat = new UserChat();
                userChat.setFromId(node.getLocalUser().getId());
                userChat.setToId(id);
                userChat.setContent(jsonObject.getStr("content"));
                userChat.setNetId(node.getNetworkId());
                userChat.setType(jsonObject.getInt("type"));
                userChat.setCreateDate(System.currentTimeMillis());
                userChatMapper.insert(userChat);
                node.write(ws, jsonObject.toString());
            } else {
                //其他节点来源消息解密，先用本机私钥解密，得到sign+content，再用发送方公钥解密，比较sign和content。
                String localPrivateKey = node.getLocalUser().getPrivateKey();
                String sendPublicKey = node.getUserByWs(webSocket).getPublicKey();
                //本地私钥解密
                String decrypt = SmUtil.sm2(localPrivateKey, null).decryptStrFromBcd(msg, KeyType.PrivateKey);
                JSONObject json = JSONUtil.parseObj(decrypt);
                //对方公钥验签
                byte[] sign = Base64.getDecoder().decode(json.getStr("sign"));
                String message = json.getStr("message");
                boolean verify = SmUtil.sm2(null, sendPublicKey).verify(message.getBytes(), sign);
                if (verify == true) {
                    JSONObject jsonObject = JSONUtil.parseObj(message);
                    Integer type = jsonObject.getInt("type");
                    if (type == 0) {/**连接其他节点*/
                        String content = jsonObject.getStr("content");
                        JSONArray jsonArray = JSONUtil.parseArray(content);
                        List<Map> nodes = jsonArray.toList(Map.class);
                        connectNode(nodes);
                    } else if(type == 12){
                        ChainData chainData = new ChainData();
                        chainData.setNetworkId(node.getNetworkId());
                        chainData.setOriginalFileName(jsonObject.getStr("name"));
                        chainData.setSender(jsonObject.getStr("sender"));
                        chainData.setTime(jsonObject.getLong("time"));
                        chainData.setStatus(jsonObject.getLong("status"));
                        chainData.setSendTime(jsonObject.getLong("sendTime"));
                        chainData.setStage(jsonObject.getInt("stage"));
                        chainData.setLevel(jsonObject.getStr("level"));
                        chainData.setType(jsonObject.getInt("docType"));
                        chainData.setSerialNum(jsonObject.getStr("serialNum"));
                        chainData.setUpdateTime(System.currentTimeMillis());
                        chainDataMapper.insert(chainData);
//                        node.getChainDataList().add(chainData);
                        node.addChainDataList(chainData);
                        node.updateChainDataTime(System.currentTimeMillis());
                    } else if(type == 13){
                        String serialNum = jsonObject.getStr("serialNum");
                        for (ChainData chainData : node.getChainDataList()) {
                            if (chainData.getSerialNum().equals(serialNum) || chainData.getSerialNum() == serialNum) {
                                chainData.setTime(jsonObject.getLong("time"));
                                chainData.setStatus(jsonObject.getLong("status"));
                                chainData.setSigns(jsonObject.getStr("signs"));
                                chainDataMapper.updateById(chainData);
                                node.updateChainDataTime(System.currentTimeMillis());
                            }
                        }
                    } else if(type == 14){
                        String str = jsonObject.getStr("chainDataList");
                        List<ChainData> chainDataList = JSONUtil.parseArray(str).toList(ChainData.class);
                        node.setChainDataList(chainDataList);
                    } else if (type == 1) {/**接收到文本信息*/
                        UserChat userChat = new UserChat();
                        userChat.setFromId(node.getIdByWebSocket(webSocket, node.getIdToIpList()));
                        userChat.setToId(node.getLocalUser().getId());
                        userChat.setContent(jsonObject.getStr("content"));
                        userChat.setNetId(node.getNetworkId());
                        userChat.setType(jsonObject.getInt("type"));
                        userChat.setCreateDate(System.currentTimeMillis());
                        userChatMapper.insert(userChat);
                        jsonObject.put("id", userChat.getFromId());
                        if (node.getBrowserClient() != null) {
                            node.write(node.getBrowserClient(), jsonObject.toString());
                        } else {
                            node.write(NodeUtil.client, jsonObject.toString());
                        }
                    } else if (type == 4) {/**接收文书*/
                        /**---------------保存本地------------------------------------*/
                        UserChat userChat = jsonObject.get("userChat", UserChat.class);
                        Document document = jsonObject.get("document", Document.class);
                        String sender = jsonObject.getStr("sender");
                        JSONArray jsonArray = jsonObject.getJSONArray("toAccount");
                        List<String> toAccount = Convert.toList(String.class, jsonArray);
                        String fileUrl = "";
                        String url = "";
                        String fileName = jsonObject.getStr("filename");
                        long l = System.currentTimeMillis();
                        fileUrl = Constants.DOC_PREFIX_PATH + File.separator + l + fileName;
                        url = Constants.RESOURCE_PREFIX + Constants.DOC_PREFIX + l + fileName;
                        byte[] file = Base64.getDecoder().decode(jsonObject.getStr("content"));
                        FileUtil.writeBytes(file, CombatDocumentConfig.getProfile() + File.separator + fileUrl);
                        /**----------------收到回传文书上链---------------------*/
                        //todo:上链接口注释
                        if (("3").equals(userChat.getDocumentStatus())) {
                            Network network = networkMapper.selectById(node.getNetworkId());
//                            AjaxResult dataByChain = EthChain.getDataByChain(network.getChainId(), network.getContract(), null, null, document.getSerialNum());
//                            String data = dataByChain.getData().toString();
//                            if(data==null|| "".equals(data)){
//                                for (int i = 0; i < 2; i++) {
//                                    dataByChain = EthChain.getDataByChain(network.getChainId(), network.getContract(), null, null, document.getSerialNum());
//                                    data = dataByChain.getData().toString();
//                                    if(data==null|| "".equals(data)){
//                                        Thread.sleep(2000l);
//                                    }else{
//                                        break;
//                                    }
//                                }
//                            }
                            String serialNum = document.getSerialNum();
                            ChainData result = null;
                            for (ChainData chainData : node.getChainDataList()) {
                                if (chainData.getSerialNum().equals(serialNum) || chainData.getSerialNum() == serialNum) {
                                    result = chainData;
                                }
                            }
                            JSONObject jsonObject1 = JSONUtil.parseObj(result);
                            Long start = (Long) jsonObject1.get("time");
                            if(start==null){
                                start = System.currentTimeMillis();
                            }
                            long end = System.currentTimeMillis();
                            jsonObject1.put("time", end);
                            jsonObject1.put("status", 1);
//                            List signs = (List) jsonObject1.get("signs");
                            Object signs1 = jsonObject1.get("signs");
                            List<Sign> signs = null;
                            if (!Objects.isNull(signs1)) {
                                signs = JSONUtil.parseArray(signs1).toList(Sign.class);
                            }
                            //查询签署者信息
                            Long userid = node.getIdByWebSocket(webSocket, node.getIdToIpList());
                            User user = userMapper.selectById(userid);
                            //文件等级
                            String docGrade = document.getDocGrade();
                            Long hour = 0l;
                            LambdaQueryWrapper<DocApprovalLimit> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(DocApprovalLimit::getNetworkId, node.getNetworkId());
                            DocApprovalLimit docApprovalLimit = docApprovalLimitMapper.selectOne(wrapper);
                            if("0".equals(docGrade)){
                                 hour = docApprovalLimit.getFirstLimittime();
                            }else  if("1".equals(docGrade)){
                                hour = docApprovalLimit.getSecondLimittime();
                            }else {
                                hour = docApprovalLimit.getThirdLimittime();
                            }
                            //组装签署者信息
                            JSONObject signer = new JSONObject();
                            signer.put("timeout", DateUtil.isTimeOut(start, end, hour));
                            signer.put("name", user.getName());
                            signer.put("time", System.currentTimeMillis());
                            signer.put("level", docGrade);
                            List list = new ArrayList();
                            if (signs == null) {
                                list.add(signer);
                            } else {
                                list = (List) signs;
                                list.add(signer);
                            }

                            jsonObject1.put("signs", list);
                            node.updateDataToPrimary(document.getSerialNum(),jsonObject1);
                            String value = Base64.getEncoder().encodeToString(jsonObject1.toString().getBytes());
                            try {
                                AjaxResult ajaxResult = EthChain.updateChain(network.getChainId(), network.getContract(), document.getSerialNum(), value);
                                if("0".equals(ajaxResult.getCode())){
                                    log.error(ajaxResult.getMessage());
                                }
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
//                                throw new BusinessException("上链失败！");
                            }
                        }

                        /**---------------插文书表------------------------------------*/
                        document.setId(null);
                        document.setContent(url);
                        document.setNetId(node.getNetworkId());
                        document.setPath(CombatDocumentConfig.getProfile() + File.separator + fileUrl);// 文书绝对地址
                        if (("0").equals(document.getStatus())) {
                            document.setStatus(1);// 状态：0-未审批；1-审批中；2-审批结束
                        } else if (("2").equals(document.getStatus())) {
                            document.setStatus(1);
                        }
                        document.setCreateDate(System.currentTimeMillis());
                        documentMapper.insert(document);
                        /**---------------插聊天表------------------------------------*/
                        userChat.setId(null);
                        userChat.setSender(sender);
                        userChat.setToAccount(String.join(",",toAccount));
                        userChat.setFromId(node.getIdByWebSocket(webSocket, node.getIdToIpList()));
                        userChat.setToId(node.getLocalUser().getId());
                        String chatUrl = Constants.HTTP + node.getLocalIp() + ":"+node.getServerPort()+ url;
                        userChat.setContent(chatUrl);
                        userChat.setDocumentId(document.getId());
                        userChat.setNetId(node.getNetworkId());
                        userChat.setType(jsonObject.getInt("type"));
                        userChat.setSerialNum(document.getSerialNum());
                        userChat.setOriginalFilename(document.getName());
                        userChat.setCreateDate(System.currentTimeMillis());

                        if (("0").equals(userChat.getDocumentStatus())) {/**已发送-》待处理*/
                            userChat.setDocumentStatus("1");
                        } else if (("3").equals(userChat.getDocumentStatus())) {/**已处理-》回传待处理*/
                            if(node.getLocalUser().getUsername().equals(sender)){
                                userChat.setDocumentStatus("2");
                            }else {
                                userChat.setDocumentStatus("1");
                            }
                        } else if (("2").equals(userChat.getDocumentStatus())) {/**回传待处理--转发后--》待处理*/
                            userChat.setDocumentStatus("1");
                        }
                        userChatMapper.insert(userChat);
                        /**---------------传至浏览器------------------------------------*/
                        url = Constants.HTTP + node.getLocalIp() + ":" + port + url;
                        jsonObject.put("id", userChat.getFromId());
                        JSONObject content = new JSONObject();
                        content.put("fileName", document.getName());
                        content.put("fileUrl", url);
                        content.put("serialNum", document.getSerialNum());
                        content.put("status", userChat.getDocumentStatus());
                        content.put("docType",document.getType());
                        content.put("createUser", document.getCreateUser());
                        content.put("userChatId", userChat.getId());
                        content.put("documentId", document.getId());
                        content.put("sender",sender);
                        content.put("toAccount",jsonObject.getJSONArray("toAccount"));
                        jsonObject.put("content", content);
                        jsonObject.remove("userChat");
                        jsonObject.remove("document");
                        jsonObject.remove("sender");
                        jsonObject.remove("toAccount");
                        if (node.getBrowserClient() != null) {
                            node.write(node.getBrowserClient(), jsonObject.toString());
                        } else {
                            node.write(NodeUtil.client, jsonObject.toString());
                        }
                    } else if (type == 5) {/**接受群公告消息*/
                        JSONObject content = jsonObject.getJSONObject("content");
                        /**群发消息插表，转发至浏览器*/
                        Broadcast broadcast = new Broadcast();
                        broadcast.setContent(content.getStr("message"));
                        broadcast.setCreateDate(content.getLong("date"));
                        broadcast.setUserId(node.getIdByWebSocket(webSocket, node.getIdToIpList()));
                        broadcast.setNetId(node.getNetworkId());
                        broadcastMapper.insert(broadcast);
                        node.write(NodeUtil.client, jsonObject.toString());
                    } else if (type == 7) {/**转发至主节点消息*/
                        //转发至主节点的，插入文书表
                        Document document = jsonObject.get("document", Document.class);
                        String fileUrl = "";
                        String url = "";
                        String fileName = jsonObject.getStr("filename");
                        long l = System.currentTimeMillis();
                        fileUrl = Constants.DOC_PREFIX_PATH + File.separator + l + fileName;
                        url = Constants.RESOURCE_PREFIX + Constants.DOC_PREFIX + l + fileName;
                        byte[] file = Base64.getDecoder().decode(jsonObject.getStr("content"));
                        FileUtil.writeBytes(file, CombatDocumentConfig.getProfile() + File.separator + fileUrl);
                        //插文书表
                        document.setId(null);
                        document.setContent(url);
                        document.setNetId(node.getNetworkId());
                        document.setPath(CombatDocumentConfig.getProfile() + File.separator + fileUrl);// 文书绝对地址
                        document.setCreateDate(System.currentTimeMillis());
                        documentMapper.insert(document);
                    } else if (type == 8) {/**接收到其他用户的新增信息，向浏览器发送*/
                        //接收到对方user，判断本地是否已存该用户
                        String content = jsonObject.getStr("content");
                        log.info("接收到User"+content);
                        User user = JSONUtil.toBean(content, User.class);
                        User username = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
                        //若无保存两张表，然后存user至list，若客户端连接则通知
                        if (username == null) {
                            user.setId(null);
                            userMapper.insert(user);
                            NetworkUser networkUser1 = new NetworkUser();
                            networkUser1.setNetworkId(node.getNetworkId());
                            networkUser1.setUserId(user.getId());
                            networkUser1.setStatus(0);
                            networkUserMapper.insert(networkUser1);
                        } else {
                            user.setId(username.getId());
                            user.setAvatarUrl(username.getAvatarUrl());
                            user.setPassword(null);
                            userMapper.updateById(user);
                            NetworkUser networkUser = networkUserMapper.selectOne(new QueryWrapper<NetworkUser>().eq("network_id", node.getNetworkId()).eq("user_id", user.getId()));
                            if(networkUser == null) {
                                NetworkUser networkUser1 = new NetworkUser();
                                networkUser1.setNetworkId(node.getNetworkId());
                                networkUser1.setUserId(user.getId());
                                networkUser1.setStatus(0);
                                networkUserMapper.insert(networkUser1);
                            }
                        }
                        /**将id、ip、ws绑定*/
                        node.getUserList().add(user);
                        node.getIdToIpList().add(new IdToIp(node.getIpByWs(webSocket), user.getId(), webSocket));
                        if (node.client != null) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("type", 8);
                            jsonObject1.put("content", JSONUtil.toJsonStr(user));
                            jsonObject1.put("id", user.getId());
                            node.write(node.client, jsonObject1.toString());
                            log.info("向浏览器推送User"+jsonObject1.toString());
                        }
                    } else if(type == 9){/**接收到阶段表+时间限制表信息*/
                        /**插入阶段表*/
                        if(jsonObject.containsKey("grade")){
                            String str = jsonObject.getStr("grade");
                            Grade grade = JSONUtil.toBean(str, Grade.class);
                            Grade gradeById = gradeMapper.selectOne(new QueryWrapper<Grade>().eq("network_id", node.getNetworkId()).eq("create_date",grade.getCreateDate()));
                            if(gradeById == null){
                                /**不跳转*/
                            }else {
                                /**修改内存标志*/
                                node.setGrade(gradeById);
                                node.setGradeIndex(node.getGradeIndex()+1);
                            }
                        }
                        /**插入时间限制表*/
                        if (jsonObject.containsKey("docApprovalLimit")){
                            String str = jsonObject.getStr("docApprovalLimit");
                            DocApprovalLimit docApprovalLimit = JSONUtil.toBean(str, DocApprovalLimit.class);
                            DocApprovalLimit docApprovalLimitById = docApprovalLimitMapper.selectOne(new QueryWrapper<DocApprovalLimit>().eq("network_id", node.getNetworkId()));
                            if(docApprovalLimitById == null){
                                docApprovalLimit.setId(null);
                                docApprovalLimit.setNetworkId(node.getNetworkId());
                                docApprovalLimitMapper.insert(docApprovalLimit);
                            }else {
                                docApprovalLimitById.setFirstLimittime(docApprovalLimit.getFirstLimittime());
                                docApprovalLimitById.setSecondLimittime(docApprovalLimit.getSecondLimittime());
                                docApprovalLimitById.setThirdLimittime(docApprovalLimit.getThirdLimittime());
                                docApprovalLimitById.setUpdateTime(docApprovalLimit.getUpdateTime());
                                docApprovalLimitMapper.updateById(docApprovalLimitById);
                            }
                        }
                    }else if( type == 11){
                        if(jsonObject.containsKey("grades")){
                            String str = jsonObject.getStr("grades");
                            List<Grade> grades = JSONUtil.parseArray(str).toList(Grade.class);
                            gradeMapper.delete(new QueryWrapper<Grade>().eq("network_id", node.getNetworkId()));
                            for(int i=0;i<grades.size();i++){
                                grades.get(i).setId(null);
                                grades.get(i).setNetworkId(node.getNetworkId());
                                gradeMapper.insert(grades.get(i));
                            }
                            node.setupGrade();
                        }
                        if (jsonObject.containsKey("docApprovalLimit")){
                            /**处理时间限制表*/
                            String jsonstr = jsonObject.getStr("docApprovalLimit");
                            DocApprovalLimit docApprovalLimit = JSONUtil.toBean(jsonstr, DocApprovalLimit.class);
                            DocApprovalLimit docApprovalLimitById = docApprovalLimitMapper.selectOne(new QueryWrapper<DocApprovalLimit>().eq("network_id", node.getNetworkId()));
                            if(docApprovalLimitById == null){
                                docApprovalLimit.setId(null);
                                docApprovalLimit.setNetworkId(node.getNetworkId());
                                docApprovalLimitMapper.insert(docApprovalLimit);
                            }else {
                                docApprovalLimitById.setFirstLimittime(docApprovalLimit.getFirstLimittime());
                                docApprovalLimitById.setSecondLimittime(docApprovalLimit.getSecondLimittime());
                                docApprovalLimitById.setThirdLimittime(docApprovalLimit.getThirdLimittime());
                                docApprovalLimitById.setUpdateTime(docApprovalLimit.getUpdateTime());
                                docApprovalLimitMapper.updateById(docApprovalLimitById);
                            }
                        }
                    }else {/**接收到图片、文件信息---保存本地、插表、发送前段*/
                        String fileUrl ="";
                        String url ="";
                        String fileName = jsonObject.getStr("filename");
                        if (type == 2) {
                            fileUrl = Constants.PIC_PREFIX_PATH + File.separator + System.currentTimeMillis() + fileName;
                            url = Constants.RESOURCE_PREFIX + Constants.PIC_PREFIX + System.currentTimeMillis() + fileName;
                        } else if (type == 3) {
                            fileUrl = Constants.FILE_PREFIX_PATH + File.separator + System.currentTimeMillis() + fileName;
                            url = Constants.RESOURCE_PREFIX + Constants.FILE_PREFIX + System.currentTimeMillis() + fileName;
                        }
                        byte[] file = Base64.getDecoder().decode(jsonObject.getStr("content"));
                        FileUtil.writeBytes(file, CombatDocumentConfig.getProfile() + File.separator + fileUrl);
                        //插表,
                        UserChat userChat = new UserChat();
                        userChat.setFromId(node.getIdByWebSocket(webSocket, node.getIdToIpList()));
                        userChat.setToId(node.getLocalUser().getId());
                        String chatUrl = Constants.HTTP + node.getLocalIp() + ":"+node.getServerPort()+ url;
                        userChat.setContent(chatUrl);
                        userChat.setNetId(node.getNetworkId());
                        userChat.setType(jsonObject.getInt("type"));
                        userChat.setOriginalFilename(fileName);
                        userChat.setCreateDate(System.currentTimeMillis());
                        userChatMapper.insert(userChat);
                        //转发至浏览器
                        url = Constants.HTTP + node.getLocalIp() + ":" + port + url;
                        jsonObject.put("id", userChat.getFromId());
                        JSONObject content = new JSONObject();
                        content.put("fileName", fileName);
                        content.put("fileUrl", url);
                        jsonObject.put("content", content);
                        if (node.getBrowserClient() != null) {
                            node.write(node.getBrowserClient(), jsonObject.toString());
                        } else {
                            node.write(NodeUtil.client, jsonObject.toString());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("处理IP地址为：" + webSocket.getRemoteSocketAddress().getAddress().toString()
                    + "的p2p错误消息:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 处理socket消息，图片类型/文件类型
     *
     * @param webSocket
     * @param msg
     */
    public void handleMessage(WebSocket webSocket, ByteBuffer msg) {
        /**先存本地，然后通过后缀判断type2/3--插入表---发送前端*/
        try {
            log.info("接收到IP地址为：" + webSocket.getRemoteSocketAddress().getAddress().toString()
                    + "的p2p消息：" + msg);
            String resourceDescriptor = webSocket.getResourceDescriptor();
            String fileExtension = getFileExtension(resourceDescriptor);
            byte[] fileData = msg.array();
            FileOutputStream fos = new FileOutputStream("url地址");
            fos.write(fileData);
        } catch (Exception e) {
            log.info("处理IP地址为：" + webSocket.getRemoteSocketAddress().getAddress().toString()
                    + "的p2p错误消息:" + e.getMessage());
        }
    }

    /**
     * 取后缀
     *
     * @param fileName
     * @return
     */
    private String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }

    /**
     * 连接其他节点方法
     */
    //完善初始化方法
    public void connectNode(List<Map> nodeList) {
        for (Map node : nodeList) {
            String ip = node.get("ip").toString();
            if (!(ip).equals("127.0.0.1")) {
                p2pClient.connectPeer("ws://" + node.get("ip").toString() + ':' + this.node.getPort());
                log.info("*****节点" + node.get("ip").toString() + "****连接成功");
            }
        }
    }


}
